Models in Django

Manish Patel

Aug 25, 2023

Models in Django

1. Models as Database Tables:

  • Theory: Django models define the structure of database tables. Each model class represents a table and its attributes represent the fields within the table.
  • Example:
class Student(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()

2. Fields and Data Types:

  • Theory: Fields define the type of data that can be stored in a model’s table column. Django provides various field types like CharField, IntegerField, DateField, etc.
  • Example:
class Book(models.Model):
    title = models.CharField(max_length=200)
    publication_date = models.DateField()

3. ORM (Object-Relational Mapping):

  • Theory: Django’s ORM allows you to interact with the database using Python objects. Model classes act as Python representations of database tables, enabling you to perform CRUD operations using Python code.
  • Example:
# Create a new book
new_book = Book(title='Django Basics', publication_date='2023-01-01')
new_book.save()

# Retrieve books
all_books = Book.objects.all()

4. Model Instances:

  • Theory: Model instances are individual records in the database represented as Python objects. You can create, update, and delete instances using Python methods.
  • Example:
book = Book.objects.get(pk=1)
book.title = 'Updated Title'
book.save()

5. QuerySets:

  • Theory: QuerySets represent database queries. You can filter, sort, and chain methods to manipulate QuerySets before executing the query.
  • Example:
# Filtering and ordering
recent_books = Book.objects.filter(publication_date__year=2023).order_by('-publication_date')

6. Migrations:

  • Theory: Migrations are scripts that manage changes to the database schema based on model changes. They ensure that the database structure stays in sync with your models.
  • Example:
python manage.py makemigrations
python manage.py migrate

7. Model Fields Options:

  • Theory: Field options provide additional behavior and constraints for model fields. They control aspects like nullability, uniqueness, and default values.
  • Example:
class Student(models.Model):
    name = models.CharField(max_length=100, unique=True)
    age = models.IntegerField(null=True)

8. Primary Keys and Relationships:

  • Theory: Primary keys uniquely identify records. Relationships like ForeignKey, OneToOneField, and ManyToManyField establish connections between models, reflecting their associations.
  • Example:
class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

9. Model Methods:

  • Theory: Model methods are Python functions defined within a model class. They encapsulate behavior related to the data stored in the model.
  • Example:
class Book(models.Model):
    title = models.CharField(max_length=200)
    publication_date = models.DateField()

    def is_recent(self):
        return self.publication_date.year >= 2020

10. Admin Interface:

  • Theory: Django’s admin interface provides a convenient way to manage model data without writing custom views. You can customize the admin interface to display and edit model data.

  • Example:

    from django.contrib import admin
    from .models import Book
    
    admin.site.register(Book)

11. Model Meta Options:

  • Theory: The Meta class within a model allows you to specify various meta options that control model-level behaviors such as ordering, verbose names, and permissions.

  • Example:

    class Book(models.Model):
        title = models.CharField(max_length=200)
        author = models.CharField(max_length=100)
    
        class Meta:
            ordering = ['-title']
            verbose_name_plural = 'Books'

12. Abstract Models and Inheritance:

  • Theory: Abstract models provide common fields and methods that can be shared among multiple models. Model inheritance allows you to create specialized models while reusing properties from a base model.

  • Example:

    class BaseModel(models.Model):
        created_at = models.DateTimeField(auto_now_add=True)
        updated_at = models.DateTimeField(auto_now=True)
    
        class Meta:
            abstract = True
    
    class Article(BaseModel):
        title = models.CharField(max_length=200)
        content = models.TextField()

13. Signals:

  • Theory: Signals allow decoupled applications to get notified when certain actions occur. Django provides signals like pre_save and post_save that you can use to perform actions in response to model events.

  • Example:

    from django.db.models.signals import post_save
    from django.dispatch import receiver
    
    @receiver(post_save, sender=Book)
    def book_saved(sender, instance, **kwargs):
        print(f"Book '{instance.title}' saved.")

14. Validations:

  • Theory: Model fields can have built-in validation mechanisms that ensure data integrity and consistency. You can also define custom validation methods to perform more complex validation checks.

  • Example:

    from django.core.exceptions import ValidationError
    
    class Book(models.Model):
        title = models.CharField(max_length=200)
    
        def clean(self):
            if 'bad' in self.title.lower():
                raise ValidationError("Title contains forbidden word.")

15. Model Managers:

  • Theory: Model managers are responsible for creating, retrieving, and querying model instances. You can define custom managers to add custom querying methods to your models.

  • Example:

    class BookManager(models.Manager):
        def bestsellers(self):
            return self.filter(rating__gte=4.0)
    
    class Book(models.Model):
        title = models.CharField(max_length=200)
        author = models.CharField(max_length=100)
        rating = models.FloatField()
    
        objects = BookManager()

Models in Django - An Example

Step 1: Create the Django Project and App

Open your terminal and run the following commands:

# Create a new Django project
django-admin startproject ModelDemo

# Change into the project directory
cd ModelDemo

# Create a new app named "blog"
python manage.py startapp blog
  • Register app in settings

Step 2: Define Models

In blog/models.py, define the Post model to represent blog posts:

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

Step 3: Configure Admin

In blog/admin.py, register the Post model with the admin site:

from django.contrib import admin
from .models import Post

admin.site.register(Post)

Step 4: Run Migrations

Run the following commands to create and apply migrations for the blog app:

python manage.py makemigrations blog
python manage.py migrate

Step 5: Create Superuser

Create a superuser account to access the Django admin interface:

python manage.py createsuperuser

Step 6: Update URLs

In blog/urls.py, create a URL pattern for viewing the list of blog posts:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.PostListView.as_view(), name='post-list'),
]

In modeldemo/urls.py,

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/', include('blog.urls')),
]

Step 7: Create Views

In blog/views.py, create a view to display the list of blog posts:

from django.views.generic import ListView
from .models import Post

class PostListView(ListView):
    model = Post
    template_name = 'blog/post_list.html'
    context_object_name = 'posts'

Step 8: Create Templates

Inside the blog/templates/blog directory, create the post_list.html template:

blog/post_list.html:

<!DOCTYPE html>
<html>
<head>
    <title>Blog Posts</title>
</head>
<body>
    <h1>Blog Posts</h1>
    <ul>
        {% for post in posts %}
            <li>{{ post.title }} - {{ post.content }}</li>
   
        {% endfor %}
    </ul>
</body>
</html>

Step 9: Run the Development Server

Run the development server:

python manage.py runserver

Step 10: Access the Blog Posts

Visit the following URL in your browser to view the list of blog posts:

  • Blog Posts: http://127.0.0.1:8000/blog/

DJANGO SHELL

  1. Open your terminal and navigate to the project directory.

  2. Start the Django shell by running the following command:

python manage.py shell
  1. In the shell, import the Blog model:
from blog.models import Post
  1. Create a new Blog instance and save it to the database:
new_post = Post(title='Sample Blog Post', content='This is a sample blog content.')
new_post.save()
  1. Exit the shell by typing:
exit()